const { each, getProperty, assert, setProperty, deepClone, deepPattenClone } = require("../../lib/tools")




module.exports = function({classes:{controller,service,mapper,serviceInter},step1,config}){
    each(step1,(entry,key)=>{
        
        const context = {
            entry
            , config
        }

        doController({entry,key,controller,config},cfg=>deepPattenClone(cfg.methods.getOne.controller,context))

        doServiceInter({entry,key,serviceInter,config},cfg=>deepPattenClone(cfg.methods.getOne.serviceInter,context))

        doService({entry,key,service,config},cfg=>deepPattenClone(cfg.methods.getOne.service,context))
    })
  
}   

function doService({entry,service,config,key},cb){
    const entryName = getProperty(entry,en=>en.base.entryClassName)
    const serv = getProperty(entryName,name=>service[name])
    logic({cls: serv,config,key},cb)
}

function doController({entry,controller,config,key},cb){
    const entryName = getProperty(entry,en=>en.base.entryClassName)
    const ctl = getProperty(entryName,name=>controller[name])
    assert(ctl,`${entryName}的控制器为空!`)

   
    logic({cls: ctl,config,key},cb)
    
   
}

function doServiceInter({entry,key,serviceInter,config},cb){
    const entryName = getProperty(entry,en=>en.base.entryClassName)
    const si = getProperty(entryName,name=>serviceInter[name])
    assert(si,`${entryName}的Service为空!`)

   
    logic({cls: si,config,key},cb)
}

function logic({cls,config,key},cb){
    const logicConfig = getProperty(config,cb)
    assert(logicConfig,`${key} Config 不能为空!`)

    if(logicConfig.fields){
        logicConfig.fields.forEach(f=>cls.fields.push(f))
    }

    if(logicConfig.imports){
        logicConfig.imports.forEach(im=>cls.imports.push(im))
    }
    
    cls.methods.push(logicConfig.method)
}